
import { Form, Input, Button } from 'antd';
import { UserWrapper } from './StyledUser';
import { useIntl, FormattedMessage } from '../../components/LangSelect';
import { login as register } from '../../api/user' 
import { useHistory } from 'react-router-dom';

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const Register = () => {
  const intl = useIntl();
  const history = useHistory();
  const onFinish = (values: any) => {
    console.log('Success:', values);
    const { username, password } = values;
    
    register({username, password}).then((res: any) => {
      history.push('/login');
    }).catch((err: any) => {
      console.log(err);
    })
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <UserWrapper>
      <div className="form-wrapper">
        <h2><FormattedMessage id="login.register" /></h2>
        <Form
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label={intl.formatMessage({id: "login.username", defaultMessage: "用户名"})}
            name="username"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label={intl.formatMessage({id: "login.password", defaultMessage: "密 码"})}
            name="password"
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            label={intl.formatMessage({id: "login.confirmpassword", defaultMessage: "确认密码"})}
            name="confirmpassword"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: 'Please confirm your password!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('The two passwords that you entered do not match!'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              <FormattedMessage id="confirm" />
            </Button>
            <Button type="link" className="fr" href="/login"><FormattedMessage id="login.logIn" /></Button>
          </Form.Item>
        </Form>
      </div>
    </UserWrapper>
  );
};

export default Register;
